<template>
  <div>
    <table border="1"
      width="700"
      style="border-collapse: collapse">
      <caption>购物车</caption>
      <thead>
        <tr>
          <th>
            <input type="checkbox" name="" id="" :checked="goodList.length===0?false:allChecked" @click="all">
            <span>全选</span>
          </th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr is='Math'
        v-for="(item,index) in goodList" :key="index"
        :obj="item"
        :index='index'
        @jianshao='js'
        @addList='addFn'
        @delList='delFn'
        ></tr>

        <tr>
          <td>合计:</td>
          <td colspan="5">{{total}}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
import Math from "./components/Math.vue"
export default {
  data(){
    return{
      goodList: [
        {
          name: "诸葛亮",
          price: 1000,
          num: 1,
          checked: false,
        },
        {
          name: "蔡文姬",
          price: 1500,
          num: 1,
          checked: false,
        },
        {
          name: "妲己",
          price: 2000,
          num: 1,
          checked: false,
        },
        {
          name: "鲁班",
          price: 2200,
          num: 1,
          checked: false,
        },
      ],
    }
  },
  components: {
    Math
  },
  computed:{
    allChecked(){
     return  this.goodList.every(item=>{return item.checked===true})
    },
    total(){
      return this.goodList.reduce((sum,item)=>{
        if(item.checked===true){
          sum+=item.price*item.num
        }
        return sum
      },0)
    }
  },
  methods:{
    all(e){
      // 需要先遍历数组,获取到数组中每一个对象中的checked属性,再把全选的checked属性赋值给每一个checked
    this.goodList.forEach(item=>{return item.checked=e.target.checked})
    },
    js(i){
      if(this.goodList[i].num>=1){
           this.goodList[i].num-=1
      }
      
      
    },
    addFn(i){
      this.goodList[i].num+=1
    },
    delFn(i){
     if(window.confirm('确定删除吗?')){
        this.goodList.splice(i,1)
     }
    }
  }
}
</script>

<style>

table,thead,tbody,th,tr,td{
  border: 1px solid black;
  text-align: center;
}
</style>